<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends BaseController
{
	//显示管理员列表
    public function getIndex(Request $request)
    {
		//获取搜索框内容
		$search=$request->input('keyword');
		$num=$request->input('pagenum',2);

		$data=DB::table('admin')->where('adm_name','like','%'.$search.'%')->paginate($num);

        return view('admin.users.index',['data'=>$data,'requset'=>$request]);
    }

	//显示添加管理员页面
  	public function getAdd(){
  		return view('admin.users.add');
  	}

	//执行添加管理员方法
  	public function postInsert(Request $request){

		//验证输入信息
		$this->validate($request,[
			'adm_name'=>'required',
			'adm_pwd'=>'required | between:6,16',
			'repadm_pwd'=>'required | between:6,16 | same:adm_pwd',


		],[
			'adm_name.required'=>'用户名不能为空',
			'adm_pwd.required'=>'密码不能为空',
			'adm_pwd.between'=>'请输入6到16个字符',
			'repadm_pwd.between'=>'请输入6到16个字符',
			'repadm_pwd.required'=>'确认密码不能为空',
			'repadm_pwd.same'=>'两次密码不一致',
		]);
		$data=$request->except('_token','repadm_pwd');
		//调用上传单张图片的方法
		$pic_name=$this->UploadOneImage('adm_face','face');
		$data['adm_pwd']=Hash::make($data['adm_pwd']);
		$data['adm_token']=str_random(50);
		$data['adm_time']=time();
		$data['adm_face']=$pic_name;


		//插入数据库
		$z=DB::table('admin')->insert($data);
		//判断插入结果
		if($z){
			return redirect('admin/user/index')->with('success','添加成功');
		}else{
			return back()->with('error','添加失败');
		}

  	}

	public function getEdit($id)
	{
		$data=DB::table('admin')->where('adm_id',$id)->first();

		return view('admin.users.edit',['data'=>$data]);
	}

	public function postUpload(Request $request,$id)
	{

		//过滤字段
		$data=$request->except('_token');
		//验证输入信息
		$this->validate($request,[
				'adm_name'=>'required',
				'adm_tel'=>'required ',
				'adm_email'=>'required | email',


		],[
				'adm_name.required'=>'用户名不能为空',
				'adm_tel.required'=>'电话不能为空',
				'adm_email.required'=>'邮箱不能为空',
				'adm_email.email'=>'邮箱格式不正确',
		]);

		//调用上传单张图片的方法
		$adm_face=$this->UploadOneImage('adm_face','face');
		$data['adm_face']=$adm_face;
		//插入数据
		$z=DB::table('admin')->where('adm_id',$id)->update($data);
		if($z){
			return redirect('admin/user/index')->with('successs','修改成功');
		}else{
			return back()->with('error','修改失败');
		}
	}

	public function getDelete($id)
	{
		$z=DB::table('admin')->where('adm_id',$id)->delete();
		if($z){
			$data=[
					'status'=>0,
			];
		}else{
			$data=[
				'status'=>1,
			];
		}
		return $data;
	}
}
